package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("sys_menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @GetMapping("/allData")
    public ResultData allData(){
        //先查pid为0的,肯定是最顶层
        LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        menuLambdaQueryWrapper.eq(Menu::getPid,0);
        List<Menu> list = menuService.list(menuLambdaQueryWrapper);

        List<MenuDto> menuDtoList = list.stream().map(s -> {
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(s, menuDto);
            return menuDto;
        }).collect(Collectors.toList());

        List<MenuDto> digui = digui(menuDtoList);

        return ResultData.ok("",digui);
    }


    public List<MenuDto> digui(List<MenuDto> dtoList){
        List<MenuDto> collect = dtoList.stream().map(s -> {
            Integer id = s.getId();
            LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
            menuLambdaQueryWrapper.eq(Menu::getPid, id);
            List<Menu> list = menuService.list(menuLambdaQueryWrapper);
            if (list.size()==0) {
                return null;
            }

            List<MenuDto> menuDtoList_angin = list.stream().map(s1 -> {
                MenuDto menuDto = new MenuDto();
                BeanUtils.copyProperties(s1, menuDto);
                return menuDto;
            }).collect(Collectors.toList());

            s.setChildren(menuDtoList_angin);

            digui(menuDtoList_angin);

            return s;

        }).collect(Collectors.toList());

        return collect;
    }




}
